# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:   smart-water-iot-test
# FileName:     crc16
# Author:      
# Datetime:    2022/4/1 12:00
# Description：
# -----------------------------------------------------------------------------------

def crc16_modbus(arg, invert=True) -> str:
    """
    crc16_modbus,循环冗余校验
    :param arg: 字符串
    :param invert: 布尔值
    :return:crc16_modbus校验结果
    """
    a = 0xFFFF
    b = 0xA001
    for byte in arg:
        a ^= ord(byte)
        for i in range(8):
            last = a % 2
            a >>= 1
            if last == 1:
                a ^= b
    argReturn = hex(a).upper()
    # 高位在左，低位在右
    return argReturn[2:6] if invert is True else argReturn[2:6][::-1]


if __name__ == '__main__':
    deviceName = "C12022050002"
    productKey = "g5rmun1E2Xl"
    timestamp = "1665569266017"
    vendorKey = "test19"
    content = f'{deviceName}{productKey}{timestamp}{vendorKey}'
    print(content)
    print(crc16_modbus(content))
